package com.erp.order.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.order.domain.ErpCollectProductSkuPackageInfo;
import com.erp.order.domain.ErpHandoverOrderInfo;
import com.erp.order.domain.ErpHandoverOrderInfoExtend;
import com.erp.order.mapper.*;
import com.erp.order.service.IErpSellerOrderLogService;
import com.erp.order.service.IErpSellerStoreProductEvaluationService;
import com.ruoyi.ae.api.RemoteAeLogisticsService;
import com.ruoyi.ae.api.RemoteAeOrderService;
import com.ruoyi.ae.api.domain.dto.OrderShipmentForTopDto;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.OrderLogType;
import com.ruoyi.common.core.enums.OrderProcessFlag;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.gather.api.RemoteCollectProductService;
import com.ruoyi.gather.api.domain.ErpCollectProductExpand;
import com.ruoyi.gather.api.domain.ErpCollectProductSku;
import com.ruoyi.order.api.domain.*;
import com.erp.order.domain.bo.ErpSellerOrderBo;
import com.erp.order.domain.vo.ErpSellerChildOrderSelVo;
import com.erp.order.domain.vo.ErpSellerOrderSelVo;
import com.erp.order.param.QueryOrderParam;
import com.erp.order.service.IErpSellerChildOrderService;
import com.erp.order.service.IErpSellerOrderService;
//import com.erp.statistics.api.RemoteOrderStatisticsService;
//import com.erp.statistics.api.domain.ErpChildOrderStatistics;
//import com.erp.statistics.api.domain.ErpOrderInfoStatistics;
import com.ruoyi.statistics.api.RemoteOrderStatisticsService;
import com.ruoyi.statistics.api.domain.ErpOrderInfoStatistics;
import com.ruoyi.ae.api.RemoteAeOrderAddrService;
import com.ruoyi.ae.api.domain.AeStoreOrderReceiptAddress;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.web.oldDomain.BaseEntity;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.gather.api.RemoteCollectProductSkuService;
import com.ruoyi.order.api.RemoteEvaluationService;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

import static com.ruoyi.common.core.utils.Threads.sleep;


/**
 * 卖家订单Service业务层处理
 *
 * @author erp
 * @date 2023-03-08
 */
@RequiredArgsConstructor
@Service
public class ErpSellerOrderServiceImpl implements IErpSellerOrderService {

    @Resource
    private RemoteCollectProductSkuService remoteCollectProductSkuService;
    @Resource
    private RemoteOrderStatisticsService remoteOrderStatisticsService;

    private final RemoteCollectProductService remoteCollectProductService;
    private final ErpSellerOrderMapper sellerOrderMapper;
    private final IErpSellerChildOrderService sellerChildOrderService;
    private final ErpSellerChildOrderMapper erpSellerChildOrderMapper;
    private final ErpSellerChildOrderExtendMapper erpSellerChildOrderExtendMapper;
    private final IErpSellerOrderLogService sellerOrderLogService;
    private final RemoteAeOrderAddrService remoteAeOrderAddrService;
    private final RemoteEvaluationService remoteEvaluationService;
    private final RemoteSellerStoreService remoteSellerStoreService;
    private final ErpSellerOrderExtendMapper erpSellerOrderExtendMapper;
    private final ErpHandoverOrderInfoMapper erpHandoverOrderInfoMapper;
    private final ErpHandoverOrderInfoExtendMapper erpHandoverOrderInfoExtendMapper;
    private final RemoteAeLogisticsService remoteAeLogisticsService;
    private final RemoteAeOrderService remoteAeOrderService;


    /**
     * 获取待组包状态下的订单商品列表
     *
     * @return
     */
    @Override
    public R<Object> getHandoverOrderStoreList() {
        List<String> storeList = sellerOrderMapper.getHandoverOrderStoreList();
        return R.ok(storeList);
    }

    @Override
    public R<Object> cutAndErrorRedReminder() {
        Map<String, Object> map = new HashMap<>();
        List<ErpSellerOrder> cutOffOrderList = sellerOrderMapper.selectList(
                new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getErpInnerOrderStatus, 501)
        );
        List<ErpSellerOrder> errorOrderList = sellerOrderMapper.selectList(
                new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderProcessFlag, "error")
        );
        map.put("cutOffNum", cutOffOrderList.size());
        map.put("errorNum", errorOrderList.size());
        return R.ok(map);
    }

    @Override
    public R<Object> redReminderForHandoverOrder() {
        //1、获取
        List<ErpSellerOrder> orderList = sellerOrderMapper.selectList(
                new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getErpInnerOrderStatus, 109)
        );
        Integer count = 0;
        Boolean flag = false;
        for (ErpSellerOrder order : orderList) {
            List<ErpSellerChildOrder> childOrders = erpSellerChildOrderMapper.selectList(
                    new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, order.getOrderId())
            );
            for (ErpSellerChildOrder childOrder : childOrders) {
                ErpHandoverOrderInfo handoverOrderInfo = erpHandoverOrderInfoMapper.selectOne(
                        new LambdaQueryWrapper<ErpHandoverOrderInfo>().like(ErpHandoverOrderInfo::getChildOrderIdList, childOrder.getChildOrderId())
                );
                if (handoverOrderInfo != null) {
                    ErpHandoverOrderInfoExtend handoverOrderInfoExtend = erpHandoverOrderInfoExtendMapper.selectOne(
                            new LambdaQueryWrapper<ErpHandoverOrderInfoExtend>().eq(ErpHandoverOrderInfoExtend::getHandoverOrderId, handoverOrderInfo.getHandoverOrderId())
                    );
                    if (handoverOrderInfoExtend == null) {
                        flag = true;
                    }
                } else {
                    flag = true;
                }
            }
            if (flag) {
                count++;
                flag = false;
            }

        }
        return R.ok(count);
    }

    @Override
    public R<Object> sellerShipmentForOther(Long orderId, Integer type) {
        ErpSellerOrderExtend orderExtend = erpSellerOrderExtendMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, orderId)
        );

        //获得该订单下应该有几个子订单
        List<ErpSellerChildOrder> childOrderSendList = erpSellerChildOrderMapper.selectList(
                new LambdaQueryWrapper<ErpSellerChildOrder>()
                        .eq(ErpSellerChildOrder::getOrderId, orderId)
        );
        //是否全部发货
        String sendType = "all";

        if (type == 1) {

            //声明发货的话需要
            //1、国际运单号 2、物流方案编码
            //send_type 默认为all
            //子交易单号
            List<OrderShipmentForTopDto.SubTradeOrder> subTradeOrderlist = new ArrayList<>();
            OrderShipmentForTopDto shipmentDto = new OrderShipmentForTopDto();
            shipmentDto.setTrade_order_id(orderId);
            //通过订单获取交易店铺
            ErpSellerOrder order = sellerOrderMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId));
            R<Object> sellerStoreEmpowerByCnCode = remoteSellerStoreService.getSellerStoreEmpowerByCnCode(order.getSellerLoginId());
            if (sellerStoreEmpowerByCnCode.getCode() != 200) {
                return R.fail("找不到店铺");
            }
            ErpSellerStoreEmpower store = JSONObject.parseObject(JSONObject.toJSONString(sellerStoreEmpowerByCnCode.getData()), ErpSellerStoreEmpower.class);
            shipmentDto.setSeller_id(store.getId());

            for (ErpSellerChildOrder childOrder : childOrderSendList) {
                OrderShipmentForTopDto.SubTradeOrder subTradeOrder = new OrderShipmentForTopDto.SubTradeOrder();
                subTradeOrder.setSend_type(sendType);
                subTradeOrder.setSub_trade_order_index(childOrder.getOrderSortId());
                List<OrderShipmentForTopDto.ShipmentList> shipmentList = new ArrayList<>();
                OrderShipmentForTopDto.ShipmentList shipment = new OrderShipmentForTopDto.ShipmentList();
                //填入信息
                shipment.setLogistics_no(orderExtend.getIntlTrackingNo());
                if (orderExtend.getLogisticsService() == null) {
                    shipment.setService_name("OTHER");
                } else {
                    shipment.setService_name(orderExtend.getLogisticsService());
                }
//                if (orderExtend.getActualCarrier() != null) {
//                    shipment.setActual_carrier(orderExtend.getActualCarrier());
//                }
                shipment.setTracking_web_site("https://t.17track.net/zh-cn?nums=" + orderExtend.getIntlTrackingNo());
                shipmentList.add(shipment);
                subTradeOrder.setShipment_list(shipmentList);
                subTradeOrderlist.add(subTradeOrder);
            }
            shipmentDto.setSub_trade_order_list(subTradeOrderlist);
            System.out.println(JSONObject.toJSON(shipmentDto));
            //将所有的信息发往Ae
            R<Object> objectR = remoteAeLogisticsService.sellerShipmentForTop(shipmentDto);
            String body = JSONObject.toJSONString(objectR.getData());
            System.out.println(body);
            String code = JSONObject.parseObject(body).getString("code");
            String msg = JSONObject.parseObject(body).getString("msg");
            if (code.equals("500")) {
                return R.fail(msg);
            }
        }

        //确认是否声明发货成功
        sleep(5000);
        R<Object> orderBaseInfo = confirmOrderShippedType(Long.valueOf(orderId), 2);
        if (orderBaseInfo.getCode() == 200) {
            return R.ok(orderBaseInfo.getMsg());
        } else {
            return R.fail(orderBaseInfo.getMsg());
        }
    }

    /**
     * 确认订单状态
     */
    public R<Object> confirmOrderShippedType(Long orderId, Integer type) {
        ErpSellerOrder order = sellerOrderMapper.queryOrderByOrderId(orderId);
        R<Object> sellerStoreEmpowerByCnCode = remoteSellerStoreService.getSellerStoreEmpowerByCnCode(order.getSellerLoginId());
        if (sellerStoreEmpowerByCnCode.getCode() != 200) {
            return R.fail("找不到店铺");
        }
        ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(JSONObject.toJSONString(sellerStoreEmpowerByCnCode.getData()), ErpSellerStoreEmpower.class);
        Map<String, String> map = new HashMap<>();
        map.put("storeId", storeEmpower.getId().toString());
        map.put("orderId", order.getOrderId().toString());
        R<Object> orderBaseInfo = remoteAeOrderService.findOrderBaseInfo(map);
        
        String body = JSONObject.toJSONString(orderBaseInfo.getData());
        System.out.println(body);
        String code = JSONObject.parseObject(body).getString("code");
        if (code.equals("200")) {
            String orderStatus = JSONObject.parseObject(body)
                    .getJSONObject("data")
                    .getJSONObject("aliexpress_trade_redefining_findorderbaseinfo_response")
                    .getJSONObject("result")
                    .getString("order_status");
            if (orderStatus.equals("WAIT_BUYER_ACCEPT_GOODS")) {
                OrderLogType orderLogType = null;
                String orderProcessFlag = null;
                String erpStatus = "107";
                //添加日志
                switch (type) {
                    case 1://菜鸟发货
                        orderLogType = OrderLogType.CaiNiaoOrderSendGoods;
                        orderProcessFlag = OrderProcessFlag.CaiNiao.getInfo();
                        erpStatus = "1072";
                        break;
                    case 2://线下发货
                        orderLogType = OrderLogType.OfflineOrderSendGoods;
                        orderProcessFlag = OrderProcessFlag.Offline.getInfo();
                        break;
                    case 3://自发货
                        orderLogType = OrderLogType.MySelfOrderSendGoods;
                        orderProcessFlag = OrderProcessFlag.MySelf.getInfo();
                        break;
                    case 4://测评单
                        orderLogType = OrderLogType.EvaluationOrderSendGoods;
                        orderProcessFlag = OrderProcessFlag.Evaluation.getInfo();
                        break;
                }
//                Long orderId, String childOrderId, OrderLogType orderLogType, String remark, String orderProcessFlagInfo,String erpStatus
                sellerOrderLogService.createOrderLog(orderId, null, orderLogType, null, orderProcessFlag, erpStatus);
                updateInnerStatusAndProcess(order.getOrderId(), "WAIT_BUYER_ACCEPT_GOODS", orderProcessFlag, erpStatus);

                return R.ok("订单目前已发货");
            } else {
                return R.fail("订单目前状态异常（" + orderStatus + "），请确认发货后再进行线下发货");
            }

        } else {
            return R.fail("订单状态异常");
        }
    }


    /**
     * 根据店铺cn码，获取最新一条的订单信息
     * @param storeUserName
     * @return
     */
    @Override
    public ErpSellerOrder getNewestOrderByStoreUserName(String storeUserName){
        return sellerOrderMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerOrder>()
                        .eq(ErpSellerOrder::getSellerOperatorLoginId, storeUserName)
                        .orderByDesc(ErpSellerOrder::getGmtCreate)
                        .last("limit 1"));
    }
    
    @Override
    public ErpSellerOrder queryOrderAndProduct(Long orderId) {
        ErpSellerOrder erpSellerOrder = sellerOrderMapper.queryOrderAndProduct(orderId);
        AeStoreOrderReceiptAddress addressByOrderId = remoteAeOrderAddrService.getAddressByOrderId(orderId);
        erpSellerOrder.setAeStoreOrderReceiptAddress(addressByOrderId);
        return erpSellerOrder;
    }

//
//
//
//    /**
//     * 查询卖家订单
//     */
//    @Override
//    public ErpSellerOrderVo queryById(Long id) {
//        return sellerOrderMapper.selectVoById(id);
//    }
//
//    /**
//     * 查询卖家订单列表
//     */
//    @Override
//    public TableDataInfo<ErpSellerOrderVo> queryPageList(ErpSellerOrderBo bo, PageQuery pageQuery) {
//        LambdaQueryWrapper<ErpSellerOrder> lqw = buildQueryWrapper(bo);
//        Page<ErpSellerOrderVo> result = sellerOrderMapper.selectVoPage(pageQuery.build(), lqw);
//        return TableDataInfo.build(result);
//    }
//
//    /**
//     * 查询卖家订单列表
//     */
//    @Override
//    public List<ErpSellerOrderVo> queryList(ErpSellerOrderBo bo) {
//        LambdaQueryWrapper<ErpSellerOrder> lqw = buildQueryWrapper(bo);
//        return sellerOrderMapper.selectVoList(lqw);
//    }
//
    private LambdaQueryWrapper<ErpSellerOrder> buildQueryWrapper(ErpSellerOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getSellerLoginId()), ErpSellerOrder::getSellerLoginId, bo.getSellerLoginId());
        lqw.eq(StringUtils.isNotBlank(bo.getSellerOperatorLoginId()), ErpSellerOrder::getSellerOperatorLoginId, bo.getSellerOperatorLoginId());
        lqw.like(StringUtils.isNotBlank(bo.getSellerSignerFullname()), ErpSellerOrder::getSellerSignerFullname, bo.getSellerSignerFullname());
        lqw.eq(StringUtils.isNotBlank(bo.getBuyerLoginId()), ErpSellerOrder::getBuyerLoginId, bo.getBuyerLoginId());
        lqw.eq(bo.getOrderId() != null, ErpSellerOrder::getOrderId, bo.getOrderId());
        lqw.eq(StringUtils.isNotBlank(bo.getBizType()), ErpSellerOrder::getBizType, bo.getBizType());
        lqw.like(StringUtils.isNotBlank(bo.getBuyerSignerFullname()), ErpSellerOrder::getBuyerSignerFullname, bo.getBuyerSignerFullname());
        lqw.eq(StringUtils.isNotBlank(bo.getGmtCreate()), ErpSellerOrder::getGmtCreate, bo.getGmtCreate());
        lqw.eq(StringUtils.isNotBlank(bo.getGmtPayTime()), ErpSellerOrder::getGmtPayTime, bo.getGmtPayTime());
        lqw.eq(StringUtils.isNotBlank(bo.getGmtUpdate()), ErpSellerOrder::getGmtUpdate, bo.getGmtUpdate());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderDetailUrl()), ErpSellerOrder::getOrderDetailUrl, bo.getOrderDetailUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderStatus()), ErpSellerOrder::getOrderStatus, bo.getOrderStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getPayAmount()), ErpSellerOrder::getPayAmount, bo.getPayAmount());
        lqw.eq(StringUtils.isNotBlank(bo.getPayCurrencyCode()), ErpSellerOrder::getPayCurrencyCode, bo.getPayCurrencyCode());
        lqw.eq(StringUtils.isNotBlank(bo.getIncrementalOrder()), ErpSellerOrder::getIncrementalOrder, bo.getIncrementalOrder());
        lqw.eq(StringUtils.isNotBlank(bo.getErpInnerOrderStatus()), ErpSellerOrder::getErpInnerOrderStatus, bo.getErpInnerOrderStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getLeftEndGoodTime()), ErpSellerOrder::getLeftEndGoodTime, bo.getLeftEndGoodTime());
        lqw.eq(bo.getHeadUserId() != null, ErpSellerOrder::getHeadUserId, bo.getHeadUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getShipmentsSolutionType()), ErpSellerOrder::getShipmentsSolutionType, bo.getShipmentsSolutionType());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerOrder::getRevision, bo.getRevision());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), ErpSellerOrder::getCreateBy, bo.getCreateBy());
        lqw.eq(bo.getCreateTime() != null, ErpSellerOrder::getCreateTime, bo.getCreateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getUpdateBy()), ErpSellerOrder::getUpdateBy, bo.getUpdateBy());
        lqw.eq(bo.getUpdateTime() != null, ErpSellerOrder::getUpdateTime, bo.getUpdateTime());
        return lqw;
    }
//
//    /**
//     * 新增卖家订单
//     */
//    @Override
//    public Boolean insertByBo(ErpSellerOrderBo bo) {
//        ErpSellerOrder add = BeanUtil.toBean(bo, ErpSellerOrder.class);
//        validEntityBeforeSave(add);
//        boolean flag = sellerOrderMapper.insert(add) > 0;
//        if (flag) {
//            bo.setId(add.getId());
//        }
//        return flag;
//    }
//
//    /**
//     * 修改卖家订单
//     */
//    @Override
//    public Boolean updateByBo(ErpSellerOrderBo bo) {
//        ErpSellerOrder update = BeanUtil.toBean(bo, ErpSellerOrder.class);
//        validEntityBeforeSave(update);
//        return sellerOrderMapper.updateById(update) > 0;
//    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSellerOrder entity) {
        //TODO 做一些数据校验,如唯一约束
    }

//    /**
//     * 批量删除卖家订单
//     */
//    @Override
//    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
//        if (isValid) {
//            //TODO 做一些业务上的校验,判断是否需要校验
//        }
//        return sellerOrderMapper.deleteBatchIds(ids) > 0;
//    }
//

    @Override
    public Boolean batchChangeStatus() {
        ErpSellerOrderBo bo = new ErpSellerOrderBo();
        bo.setIncrementalOrder("2");
        LambdaQueryWrapper<ErpSellerOrder> queryWrapper = buildQueryWrapper(bo);
        List<ErpSellerOrder> orderList = sellerOrderMapper.selectList(queryWrapper);
        for (ErpSellerOrder erpSellerOrder : orderList) {
            erpSellerOrder.setIncrementalOrder("1");
        }
        return sellerOrderMapper.updateBatchById(orderList);
    }


    @Override
    public int setInnerStatus(Long orderId, String status, String flag) {
        ErpSellerOrder erpSellerOrder = sellerOrderMapper
                .selectOne(new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId));
        erpSellerOrder.setErpInnerOrderStatus(status);
        erpSellerOrder.setOrderProcessFlag(flag);
        int update = sellerOrderMapper.updateById(erpSellerOrder);
        if (update < 1) {
            throw new RuntimeException("提交异常，请重试");
        }
        return update;
    }

    @Override
    @Transactional
    public R<Object> chooseSelfShipments(String orderIds) {
        try {
            List<String> orderIdList = ListUtil.toList(orderIds.split(","));
            for (String orderIdStr : orderIdList) {
                Long orderId = Long.valueOf(orderIdStr);
                //创建childOrderExtend
                List<ErpSellerChildOrder> childOrders = erpSellerChildOrderMapper.selectList(
                        new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, orderId)
                );
                for (ErpSellerChildOrder childOrder : childOrders) {
                    ErpSellerChildOrderExtend childOrderExtend = erpSellerChildOrderExtendMapper.selectOne(
                            new LambdaQueryWrapper<ErpSellerChildOrderExtend>().eq(ErpSellerChildOrderExtend::getChildOrderId, childOrder)
                    );
                    if (childOrderExtend == null) {
                        childOrderExtend = new ErpSellerChildOrderExtend();
                        childOrderExtend.setOrderId(orderId);
                        childOrderExtend.setChildOrderId(Long.valueOf(childOrder.getChildOrderId()));
                    }
                    childOrderExtend.setType(2);
                    erpSellerChildOrderExtendMapper.insertOrUpdate(childOrderExtend);
                }
                //增加日志
                sellerOrderLogService.createOrderLog(orderId, null, OrderLogType.OrderSelfShipping,
                        null, OrderProcessFlag.MySelf.getInfo(), "111");
                //订单状态修改为111自发货
                setInnerStatus(orderId, "111", OrderProcessFlag.MySelf.getInfo());

            }
            return R.ok("已将订单状态改为自发货");
        } catch (Exception e) {
            return R.fail("订单状态修改失败");
        }


    }


    @Override
    @Transactional
    public R<Object> uploadPurchaseInfo(Long childOrderId, String proof, String purchasePrice, String cnTrackingNo) {
        try {
            ErpSellerChildOrderExtend childOrderExtend = erpSellerChildOrderExtendMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerChildOrderExtend>().eq(ErpSellerChildOrderExtend::getChildOrderId, childOrderId)
            );
            ErpSellerChildOrder childOrder = erpSellerChildOrderMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getChildOrderId, childOrderId)
            );
            if (childOrderExtend == null) {
                childOrderExtend = new ErpSellerChildOrderExtend();
                childOrderExtend.setOrderId(childOrder.getOrderId());
                childOrderExtend.setChildOrderId(childOrderId);
            }
            childOrderExtend.setProof(proof);
            childOrderExtend.setPurchasePrice(Double.valueOf(purchasePrice));
            childOrderExtend.setCnTrackingNo(cnTrackingNo);

            erpSellerChildOrderExtendMapper.insertOrUpdate(childOrderExtend);
            List<String> orderIds = new ArrayList<>();
            orderIds.add(childOrderExtend.getOrderId().toString());
            List<ErpSellerChildOrder> erpSellerChildOrders = erpSellerChildOrderMapper.selectList(
                    new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, orderIds));
            Boolean flag = true;

            if (erpSellerChildOrders.size() > 1) {
                for (ErpSellerChildOrder order : erpSellerChildOrders) {
                    childOrderExtend = erpSellerChildOrderExtendMapper.selectOne(
                            new LambdaQueryWrapper<ErpSellerChildOrderExtend>().eq(ErpSellerChildOrderExtend::getChildOrderId, order.getChildOrderId())
                    );
                    if (ObjectUtils.isNotEmpty(childOrderExtend)) {
                        if (ObjectUtils.isNotEmpty(childOrderExtend.getCnTrackingNo())) {
                            flag = false;
                        }
                    } else {
                        flag = false;
                    }
                }
            }

            if (flag) {
//                R<Object> objectR = orderLogService.checkOrderLog(childOrderExtend.getOrderId(), OrderLogType.FillInProcurementInformation, OrderProcessFlag.MySelf.getInfo());
//                if (objectR.getCode() == 500) {
                    //增加订单日志
                    sellerOrderLogService.createOrderLog(childOrderExtend.getOrderId(), null, OrderLogType.FillInProcurementInformation,
                            null, OrderProcessFlag.MySelf.getInfo(), "112");
                    //修改状态
                    setInnerStatus(childOrderExtend.getOrderId(), "112", OrderProcessFlag.MySelf.getInfo());
                    return R.ok("已填写完采购信息，待声明发货");
//                } else {
//                    return R.ok("已修改采购信息，待声明发货");
//                }
            } else {
                return R.ok("还有其他子订单信息待填写");
            }
        } catch (Exception e) {
            return R.fail("填写信息失败，请联系管理员");
        }

    }

    /**
     * 自发货 声明发货
     *
     * @param erpSellerOrderExtend
     * @return
     */
    @Override
    public R<Object> sellerShipmentForMyself(ErpSellerOrderExtend erpSellerOrderExtend) {
//        Long orderId = erpSellerOrderExtend.getOrderId();
//
//        //保存信息
//        ErpSellerOrderExtend extend = erpSellerOrderExtendMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, orderId)
//        );
//        
//        if (extend == null) {
//            extend = new ErpSellerOrderExtend();
//            extend.setOrderId(orderId);
//        }
//        extend.setIsCainiao(erpSellerOrderExtend.getIsCainiao());
//        extend.setIntlTrackingNo(erpSellerOrderExtend.getIntlTrackingNo());
//        extend.setLogisticsService(erpSellerOrderExtend.getLogisticsService());
//        extend.setType(erpSellerOrderExtend.getType());
//        erpSellerOrderExtendMapper.insertOrUpdate(extend);
//
//        if (erpSellerOrderExtend.getType().equals("1")) {
//            //使用声明发货
//            AeOrderShipmentForOther aeOrderShipmentForOther = new AeOrderShipmentForOther();
//            aeOrderShipmentForOther.setLogisticsService(erpSellerOrderExtend.getLogisticsService());
//            aeOrderShipmentForOther.setOtherExpenses(erpSellerOrderExtend.getOtherLogisticsPrice());
//            aeOrderShipmentForOther.setLogisticsNo(erpSellerOrderExtend.getIntlTrackingNo());
//            aeOrderShipmentForOther.setFreight(erpSellerOrderExtend.getRealityLogisticsPrice());
//            aeOrderShipmentForOther.setOrderId(orderId);
//            R<String> stringR = sellerShipmentForOther(aeOrderShipmentForOther);
//            System.out.println(stringR);
//            if (stringR.getCode() == 500) {
//                return R.fail(stringR.getMsg());
//            }
//        }
//
//        //4、增加日志
//        sleep(5000);
//        R<Object> orderBaseInfo = confirmOrderShippedType(Long.valueOf(orderId), 3);
//        if (orderBaseInfo.getCode() == 200) {
//            String remark = null;
//            if (erpSellerOrderExtend.getType().equals("1")) {
//                remark = "自发货成功,且从系统声明发货";
//            } else {
//                remark = "自发货成功,未从系统声明发货";
//            }
//
//            OrderLogType orderLogType = OrderLogType.MySelfOrderSendGoods;
//            iErpSellerOrderLogService.createOrderLog(orderId, null, orderLogType, remark, OrderProcessFlag.MySelf.getInfo(), "107");
//
//            setInnerStatus(orderId, "107", OrderProcessFlag.MySelf.getInfo());
//
//            return R.ok(orderBaseInfo.getMsg());
//        } else {
//            return R.fail(orderBaseInfo.getMsg());
//        }
        return R.fail();
    }
    
    

    /**
     * 上传发货信息
     *
     * @return
     */
    @Override
    @Transactional
    public R<Object> uploadSendInfo(ErpSellerOrderExtend erpSellerOrderExtend) {
        try {
            Long orderId = erpSellerOrderExtend.getOrderId();
            //存入订单统计表中

            //1、保存
            ErpSellerOrderExtend orderExtend = erpSellerOrderExtendMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, orderId)
            );
            if (orderExtend == null) {
                orderExtend = new ErpSellerOrderExtend();
                orderExtend.setOrderId(orderId);
            }
            orderExtend.setIntlTrackingNo(erpSellerOrderExtend.getIntlTrackingNo());
            orderExtend.setOtherLogisticsPrice(erpSellerOrderExtend.getOtherLogisticsPrice());
            orderExtend.setIsCainiao(erpSellerOrderExtend.getIsCainiao());
            orderExtend.setRealityLogisticsPrice(erpSellerOrderExtend.getRealityLogisticsPrice());
            orderExtend.setLogisticsProof(erpSellerOrderExtend.getLogisticsProof());
            orderExtend.setLogisticsService(erpSellerOrderExtend.getLogisticsService());
            erpSellerOrderExtendMapper.insertOrUpdate(orderExtend);


            return R.ok("信息保存成功");
        } catch (Exception e) {
            return R.fail("信息保存异常");
        }
    }

    @Override
    public R<Object> updateInnerStatusAndProcess(Long orderId, String aeOrderStatus, String orderProcessFlag, String erpOrderStatus) {
        ErpSellerOrder erpSellerOrder = sellerOrderMapper
                .selectOne(new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId));
        erpSellerOrder.setErpInnerOrderStatus(erpOrderStatus);
        erpSellerOrder.setOrderStatus(aeOrderStatus);
        erpSellerOrder.setOrderProcessFlag(orderProcessFlag);
        int update = sellerOrderMapper.updateById(erpSellerOrder);
        if (update != 1) {
            throw new RuntimeException("提交异常，请重试");
        }
        return R.ok("修改订单状态成功");

    }

    /**
     * 更新线上物流订单状态的物流费用
     *
     * @param orderId
     * @return
     */
    @Override
    public R<Object> queryLogisticsOrderDetail(Long orderId) {
//        ErpSellerOrder order = erpSellerOrderMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId)
//        );
//        if (order == null) {
            return R.fail("订单不存在");
//        }

//        //获取当前订单extend表
//        ErpSellerOrderExtend orderExtend = erpSellerOrderExtendMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, orderId)
//        );
//        if (orderExtend == null) {
//            //重新生成
//            orderExtend = new ErpSellerOrderExtend();
//            orderExtend.setOrderId(orderId);
//        }
//        Map<String, Object> map = new HashMap<>();
//        map.put("trade_order_id", orderId);
//        Long storeId = iErpSellerStoreEmpowerService.queryBySellerLoginId(order.getSellerLoginId());
//        map.put("store_id", storeId);
//        //将所有的信息发往Ae
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpLogistics/queryLogisticsOrderDetail", map, String.class);
//        String body = (String) forEntity.getBody();
//        System.out.println(body);
//        String code = JSONObject.parseObject(body).getString("code");
//        String msg = JSONObject.parseObject(body).getString("msg");
//        if (!code.equals("200")) {
//            orderExtend.setLogisticsType("店铺授权失效");
//            orderExtend.setRealityLogisticsPrice(null);
//            erpSellerOrderExtendMapper.insertOrUpdate(orderExtend);
//            return R.fail("店铺授权失效");
//        } else {
//            if (!msg.contains("logistics_fee")) {
//                orderExtend.setLogisticsType("订单可能未通过菜鸟发货");
//                orderExtend.setRealityLogisticsPrice(null);
//                erpSellerOrderExtendMapper.insertOrUpdate(orderExtend);
//                return R.fail("订单可能未通过菜鸟发货");
//            }
//
//            String orderDetailDto = JSONObject.parseObject(msg)
//                    .getJSONObject("aliexpress_logistics_querylogisticsorderdetail_response")
//                    .getJSONObject("result")
//                    .getJSONObject("result_list")
//                    .getString("aeop_logistics_order_detail_dto");
//
//            List<Dict> dicts = JsonUtils.parseArrayMap(orderDetailDto);
//            String gmtCreate = null;
//            String orderGmtCreate = null;
//            String logisticsStatus = null;
//            //物流费用
//            Double amount = null;
//            String logisticsFee = null;
//            //币种
//            String currencyCode = null;
//            //当前汇率
//            BigDecimal newUsdExchange = iErpUsdExchangeService.getNewUsdExchange();
//            int res = 0;
//            Dict dict = null;
//            if (dicts.size() > 1) {
//                for (Dict dictFor : dicts) {
//                    if (dictFor.get("logistics_status").toString().equals("last_mile_sign_in_success")){
//                        dict = dictFor;
//                    break;
//                    }
//                }
//            } else {
//                dict = dicts.get(0);
//            }
//            if (ObjectUtils.isEmpty(dict)){
//                orderExtend.setLogisticsType("请线下确认订单物流信息");
//                orderExtend.setRealityLogisticsPrice(null);
//                erpSellerOrderExtendMapper.insertOrUpdate(orderExtend);
//                return R.fail("请线下确认订单物流信息");
//            }
//
//            logisticsStatus = dict.get("logistics_status").toString();
//            if (Objects.isNull(logisticsStatus)) {
//                orderExtend.setLogisticsType("订单状态为空");
//                orderExtend.setRealityLogisticsPrice(null);
//                erpSellerOrderExtendMapper.insertOrUpdate(orderExtend);
//                return R.fail("订单状态为空");
//            } else if (logisticsStatus.equals("order_closed")) {
//                orderExtend.setLogisticsType(logisticsStatus);
//                orderExtend.setRealityLogisticsPrice(null);
//                erpSellerOrderExtendMapper.insertOrUpdate(orderExtend);
//                return R.fail("订单关闭");
//            }
//            //获取运费
//            if (ObjectUtils.isEmpty(dict.get("logistics_fee").toString())) {
//                return R.fail("订单费用不存在");
//            }
//            System.out.println(dict.get("logistics_fee").toString());
//            Map<String, Object> logisticsFeeMap = (Map<String, Object>) dict.get("logistics_fee");
//            amount = (Double) logisticsFeeMap.get("amount");
//            if (amount == Double.valueOf(0)) {
//                //处理logistics_fee_list
//
//                Map<String, Object> map1 = (Map<String, Object>) dict.get("logistics_fee_list");
//                // 解析输入字符串为JSONObject
//                JSONObject jsonObject = new JSONObject(map1);
//
//                // 获取"money"字段的值，并转换为JSONArray
//                JSONArray moneyArray = jsonObject.getJSONArray("money");
//
//                // 从JSONArray中获取第一个元素，并将其转换为JSONObject
//                JSONObject moneyObject = moneyArray.getJSONObject(0);
//                if (moneyArray.size() == 1) {
//                    amount = moneyObject.getDouble("amount");
//                } else {
//                    amount = Double.valueOf(-1);
//                }
//            }
//            currencyCode = (String) logisticsFeeMap.get("currency_code");
//            if (currencyCode.equals("USB")) {
//                //是美元，进行换算
//                //获取当前汇率
//                BigDecimal newAmount = new BigDecimal(amount).multiply(BigDecimal.valueOf(100)).divide(newUsdExchange, BigDecimal.ROUND_CEILING);
//                logisticsFee = newAmount.toString();
//            } else {
//                logisticsFee = amount.toString();
//            }
//
//            orderExtend.setLogisticsType(logisticsStatus);
//            orderExtend.setRealityLogisticsPrice(logisticsFee);
//            erpSellerOrderExtendMapper.insertOrUpdate(orderExtend);
//            return R.ok("更新状态成功");
//        }
    }

//    /**
//     * 更新订单物流费用
//     *
//     * @param orderId
//     */
//    public void updateOrderStatusXXjob(Long orderId) {
//        ErpSellerOrder order = erpSellerOrderMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId)
//        );
//        if (order == null) {
//            return;
//        }
//        Map<String, Object> map = new HashMap<>();
//        map.put("trade_order_id", orderId);
//        Long storeId = iErpSellerStoreEmpowerService.queryBySellerLoginId(order.getSellerLoginId());
//        map.put("store_id", storeId);
//        //将所有的信息发往Ae
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpLogistics/queryLogisticsOrderDetail", map, String.class);
//        String body = (String) forEntity.getBody();
//        System.out.println(body);
//        String code = JSONObject.parseObject(body).getString("code");
//        String msg = JSONObject.parseObject(body).getString("msg");
//        if (!code.equals("200")) {
//            return;
//        } else {
//            //需要确定total_page不为0
//            String totalPage = JSONObject.parseObject(msg)
//                    .getJSONObject("aliexpress_logistics_querylogisticsorderdetail_response")
//                    .getJSONObject("result")
//                    .getString("total_page");
//            if (totalPage.equals("0")) {
//                return;
//            }
//            String orderDetailDto = JSONObject.parseObject(msg)
//                    .getJSONObject("aliexpress_logistics_querylogisticsorderdetail_response")
//                    .getJSONObject("result")
//                    .getJSONObject("result_list")
//                    .getString("aeop_logistics_order_detail_dto");
//
//            List<Dict> dicts = JsonUtils.parseArrayMap(orderDetailDto);
//            //物流费用
//            Double amount = null;
//            String logisticsFee = "0";
//            //币种
//            String currencyCode = null;
//            //当前汇率
//            BigDecimal newUsdExchange = iErpUsdExchangeService.getNewUsdExchange();
//            String gmtCreate = null;
//            String orderGmtCreate = null;
//            String logisticsStatus = null;
//            int res = 0;
//            for (Dict dict : dicts) {
//                System.out.println(dict);
//                //获取当前时间的状态
//                logisticsStatus = (String) dict.get("logistics_status");
//                if (StringUtils.isEmpty(logisticsStatus)) {
//                    continue;
//                }
//                orderGmtCreate = dict.get("gmt_create").toString();
//                if (gmtCreate == null) {
//                    gmtCreate = orderGmtCreate;
//                } else {
//                    //比较时间先后
//                    res = orderGmtCreate.compareTo(gmtCreate);
//                    if (res > 0) {
//                        //orderGmtCreate > gmtCreate
//                        gmtCreate = orderGmtCreate;
//                    } else {
//                        continue;
//                    }
//                }
//                Object logistics_fee = dict.get("logistics_fee");
//                System.out.println(logistics_fee);
//                if (ObjectUtils.isEmpty(logistics_fee)) {
//                    continue;
//                }
//                //获取运费
//                System.out.println(dict.get("logistics_fee").toString());
//                Map<String, Object> logisticsFeeMap = (Map<String, Object>) dict.get("logistics_fee");
//                if (logisticsFeeMap == null) {
//                    continue;
//                }
//                amount = (Double) logisticsFeeMap.get("amount");
//                if (amount == Double.valueOf(0)) {
//                    //处理logistics_fee_list
//
//                    Map<String, Object> map1 = (Map<String, Object>) dict.get("logistics_fee_list");
//                    // 解析输入字符串为JSONObject
//                    JSONObject jsonObject = new JSONObject(map1);
//
//                    // 获取"money"字段的值，并转换为JSONArray
//                    JSONArray moneyArray = jsonObject.getJSONArray("money");
//
//                    // 从JSONArray中获取第一个元素，并将其转换为JSONObject
//                    JSONObject moneyObject = moneyArray.getJSONObject(0);
//                    if (moneyArray.size() == 1) {
//                        amount = moneyObject.getDouble("amount");
//                    } else {
//                        amount = Double.valueOf(-1);
//                    }
//                }
//                currencyCode = (String) logisticsFeeMap.get("currency_code");
//                if (currencyCode.equals("USB")) {
//                    //是美元，进行换算
//                    //获取当前汇率
//                    BigDecimal newAmount = new BigDecimal(amount).multiply(BigDecimal.valueOf(100)).divide(newUsdExchange, BigDecimal.ROUND_CEILING);
//                    logisticsFee = newAmount.toString();
//                } else {
//                    logisticsFee = amount.toString();
//                }
//            }
//            //获取当前订单extend表
//            ErpSellerOrderExtend orderExtend = erpSellerOrderExtendMapper.selectOne(
//                    new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, orderId)
//            );
//            if (orderExtend == null) {
//                //重新生成
//                orderExtend = new ErpSellerOrderExtend();
//                orderExtend.setOrderId(orderId);
//            }
//            orderExtend.setLogisticsType(logisticsStatus);
//            orderExtend.setRealityLogisticsPrice(logisticsFee);
//
//            erpSellerOrderExtendMapper.insertOrUpdate(orderExtend);
//
//            ErpOrderInfoStatistics orderInfoStatistics = erpOrderInfoStatisticsMapper.selectOne(
//                    new LambdaQueryWrapper<ErpOrderInfoStatistics>().eq(ErpOrderInfoStatistics::getOrderId, orderId)
//            );
//            if (orderInfoStatistics != null) {
//                orderInfoStatistics.setLogisticsPrice(logisticsFee);
//                orderInfoStatisticsMapper.updateById(orderInfoStatistics);
//            }
//            return;
//        }
//    }
//
//    public void updateLogisticsOrderStatusXXjob(Long orderId) {
//        ErpSellerOrder order = erpSellerOrderMapper.queryOrderByOrderId(orderId);
//        ErpSellerStoreEmpower store = erpSellerStoreEmpowerMapper.selectStoreByStoreUserName(order.getSellerLoginId());
//        if (Objects.isNull(store)) {
//            return;
//        }
//        Map<String, Object> sendMap = new HashMap<>();
//        sendMap.put("orderId", order.getOrderId());
//        sendMap.put("storeId", store.getId());
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpOrder/findOrderBaseInfo", sendMap, String.class);
//        String body = (String) forEntity.getBody();
//        if (!body.contains("aliexpress_trade_redefining_findorderbaseinfo_response")) {
//            return;
//        }
//        String data = JSONObject.parseObject(body).getString("data");
//        String logisticsStatus = JSONObject.parseObject(data)
//                .getJSONObject("aliexpress_trade_redefining_findorderbaseinfo_response")
//                .getJSONObject("result")
//                .getString("logistics_status");
//        String orderStatus = JSONObject.parseObject(data)
//                .getJSONObject("aliexpress_trade_redefining_findorderbaseinfo_response")
//                .getJSONObject("result")
//                .getString("order_status");
//        ErpSellerOrderExtend orderExtend = erpSellerOrderExtendMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, orderId)
//        );
//        if (orderExtend == null) {
//            orderExtend = new ErpSellerOrderExtend();
//            orderExtend.setOrderId(orderId);
//        }
//        orderExtend.setOrderStatus(orderStatus);
//        orderExtend.setLogisticsStatus(logisticsStatus);
//        erpSellerOrderExtendMapper.insertOrUpdate(orderExtend);
//    }
//
//    @Override
//    public R<Object> getOnlineLogisticsInfo(Long orderId) {
//        ErpSellerOrder order = erpSellerOrderMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId)
//        );
//        if (order == null) {
//            return R.fail("订单不存在");
//        }
//        Map<String, Object> map = new HashMap<>();
//        map.put("order_id", orderId);
//        Long storeId = iErpSellerStoreEmpowerService.queryBySellerLoginId(order.getSellerLoginId());
//        map.put("store_id", storeId);
//        //将所有的信息发往Ae
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpLogistics/getOnlineLogisticsInfo", map, String.class);
//        String body = (String) forEntity.getBody();
//        System.out.println(body);
//        String code = JSONObject.parseObject(body).getString("code");
//        if (!code.equals("200")) {
//            System.out.println(JSONObject.parseObject(body).getString("msg"));
//            System.out.println(JSONObject.parseObject(body).getString("data"));
//            return R.ok("订单信息查询成功");
//        } else {
//            return R.fail("订单信息查询失败");
//        }
//    }
//
//    public R<String> sellerShipmentForOther(AeOrderShipmentForOther aeOrderShipmentForOther) {
//        Long orderId = aeOrderShipmentForOther.getOrderId();
//        //获得该订单下应该有几个子订单
//        List<ErpSellerChildOrder> childOrderList = erpSellerChildOrderMapper.selectList(
//                new LambdaQueryWrapper<ErpSellerChildOrder>()
//                        .eq(ErpSellerChildOrder::getOrderId, orderId)
//        );
//        //是否全部发货
//        String sendType = "all";
//
//        //声明发货的话需要
//        //1、国际运单号 2、物流方案编码
//        //send_type 默认为all
//        //子交易单号
//        List<OrderShipmentForTopDto.SubTradeOrder> subTradeOrderlist = new ArrayList<>();
//        OrderShipmentForTopDto shipmentDto = new OrderShipmentForTopDto();
//        shipmentDto.setTrade_order_id(orderId);
//        //通过订单获取交易店铺
//        ErpSellerOrder order = erpSellerOrderMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId));
//        ErpSellerStoreEmpower store = iErpSellerStoreEmpowerService.getEmpowerStoreByUserNick(order.getSellerLoginId());
//        shipmentDto.setSeller_id(store.getId());
//
//        for (ErpSellerChildOrder childOrder : childOrderList) {
//            OrderShipmentForTopDto.SubTradeOrder subTradeOrder = new OrderShipmentForTopDto.SubTradeOrder();
//            subTradeOrder.setSend_type(sendType);
//            subTradeOrder.setSub_trade_order_index(childOrder.getOrderSortId());
//            List<OrderShipmentForTopDto.ShipmentList> shipmentList = new ArrayList<>();
//            OrderShipmentForTopDto.ShipmentList shipment = new OrderShipmentForTopDto.ShipmentList();
//            //填入信息
//            shipment.setLogistics_no(aeOrderShipmentForOther.getLogisticsNo());
//            if (aeOrderShipmentForOther.getLogisticsService() == null) {
//                shipment.setService_name("OTHER");
//            } else {
//                shipment.setService_name(aeOrderShipmentForOther.getLogisticsService());
//            }
//            if (aeOrderShipmentForOther.getActualCarrier() != null) {
//                shipment.setActual_carrier(aeOrderShipmentForOther.getActualCarrier());
//            }
//            shipment.setTracking_web_site("https://t.17track.net/zh-cn?nums=" + aeOrderShipmentForOther.getLogisticsNo());
//            shipmentList.add(shipment);
//            subTradeOrder.setShipment_list(shipmentList);
//            subTradeOrderlist.add(subTradeOrder);
//        }
//        shipmentDto.setSub_trade_order_list(subTradeOrderlist);
//        System.out.println(JSONObject.toJSON(shipmentDto));
//        //将所有的信息发往Ae
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpLogistics/sellerShipmentForTop", shipmentDto, String.class);
//        String body = (String) forEntity.getBody();
//        System.out.println(body);
//        String code = JSONObject.parseObject(body).getString("code");
//        String msg = JSONObject.parseObject(body).getString("msg");
//        if (code.equals("500")) {
//            return R.fail(msg);
//        }
//        //将运费保存至统计表中
//        if (aeOrderShipmentForOther.getLogisticsService() == null) {
//            ErpOrderInfoStatistics orderInfoStatistics = orderInfoStatisticsMapper.selectOne(new LambdaQueryWrapper<ErpOrderInfoStatistics>().eq(ErpOrderInfoStatistics::getOrderId, orderId));
//            if (orderInfoStatistics != null) {
//                String freight = aeOrderShipmentForOther.getFreight();
//                String otherExpenses = aeOrderShipmentForOther.getOtherExpenses();
//                // 总费用
//                BigDecimal totalFreight = new BigDecimal(freight).add(new BigDecimal(otherExpenses));
//                orderInfoStatistics.setLogisticsPrice(totalFreight.toString());
//                orderInfoStatisticsMapper.updateById(orderInfoStatistics);
//            }
//        }
//
//        return R.ok("发货成功");
//    }
    

//    @Override
//    public R<Object> getErpAgentBranchInfoByStore(String storeStr) {
//        List<String> storeList = ListUtil.toList(storeStr.split(","));
//        List<Map<String, String>> list = new ArrayList<>();
//
//        //718 展示店铺层级 公司+代理+个人ERP
//        for (String store : storeList) {
//            List<ErpSellerStoreEmpower> empowerList = erpSellerStoreEmpowerMapper.selectListByStoreUserName(store);
//            ErpUserInfo userInfo = new ErpUserInfo();
//            SysUser sysUser = new SysUser();
//            ErpAgentInfo agent = new ErpAgentInfo();
//            ErpBranchOfficeInfo branch = new ErpBranchOfficeInfo();
//            if (empowerList.size() > 0) {
//                for (ErpSellerStoreEmpower empower : empowerList) {
//                    userInfo = erpUserInfoMapper.selectOne(
//                            new LambdaQueryWrapper<ErpUserInfo>().eq(ErpUserInfo::getUserId, empower.getUserId())
//                    );
//                    if (userInfo == null) {
//                        continue;
//                    }
//                    sysUser = sysUserMapper.selectUserById(userInfo.getUserId());
//
//                    branch = erpBranchOfficeInfoMapper.selectById(userInfo.getBranchId());
//                    agent = erpAgentInfoMapper.selectById(userInfo.getAgentId());
//                    Map<String, String> infoMap = new HashMap<>();
//                    if (userInfo != null) {
//                        infoMap.put("userInfo", sysUser.getUserName() + " | " + userInfo.getCode() + " | " + userInfo.getRealName());
//                    } else {
//                        infoMap.put("userInfo", null);
//                    }
//                    if (agent != null) {
//                        infoMap.put("agent", agent.getCorporateName());
//                    } else {
//                        infoMap.put("agent", null);
//                    }
//                    if (branch != null) {
//                        infoMap.put("branch", branch.getCorporateName());
//                    } else {
//                        infoMap.put("branch", null);
//                    }
//                    list.add(infoMap);
//                }
//            }
//        }
//        return R.ok(list);
//    }

//    @Override
//    public void returnLogisticsCharges(ErpOrderReturnLogisticsPrice order) {
        //获取延伸表信息
//        ErpSellerOrderExtend orderExtend = erpSellerOrderExtendMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, order.getTradeOrderId())
//        );
//        if (orderExtend == null) {
//            return;
//        }
//        ErpSellerStoreEmpower storeEmpower = erpSellerStoreEmpowerMapper.selectStoreByStoreUserName(order.getSellerLoginId());
//
//        //进行退运费
//        re.updateWallet(FlowType.INCOME.getCode(), ExpenseType.RETUENLOGISTICSFEE.getCode(), PayType.XT.getCode(), new BigDecimal(order.getRealityLogisticsPrice()), storeEmpower.getUserId(), order.getTradeOrderId().toString(), "菜鸟物流订单在订单完成后退运费");
//
//        //退费成功则添加标记
//        orderExtend.setReturnFreightStatus("1");
////        orderExtend.setReturnFreight(order.getRealityLogisticsPrice());
//        erpSellerOrderExtendMapper.updateById(orderExtend);
//    }

//    /**
//     * 处理后付费
//     *
//     * @param order
//     */
//    @Override
//    public void disposeBehindErpPayOrder(ErpSellerOrder order) {
//        ErpSellerOrderExtend orderExtend = erpSellerOrderExtendMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, order.getOrderId())
//        );
//        R<Object> objectR = new R<>();
//        if (orderExtend.getLogisticsStatus().equals("BUYER_ACCEPT_GOODS") && orderExtend.getOrderStatus().equals("FINISH")) {
//            objectR = freezeOrderAmount(order.getOrderId(), 1);
//        } else {
//            objectR = freezeOrderAmount(order.getOrderId(), 2);
//        }
//
//        Integer code = objectR.getCode();
//        if (code == 200) {
//            orderExtend.setBehindErpPayStatus("1");
//        }
//
//    }


//    @Override
//    public TableDataInfo<ErpSellerOrder> markShipment(QueryOrderParam bo, PageQuery pageQuery) {
//        bo.setErpInnerOrderStatus("107");
//        Page<ErpSellerOrder> orderPage = sellerOrderMapper.getOrderAndChildOrderList(pageQuery.build(), bo);
//        List<ErpSellerOrder> orderList = orderPage.getRecords();
//        for (ErpSellerOrder sellerOrder : orderList) {
//            List<ErpSellerChildOrder> childOrderList = sellerOrder.getSellerChildOrderList();
//            for (ErpSellerChildOrder childOrder : childOrderList) {
//                ErpSendOutGoods sendOutGoods = sendOutGoodsService.getSendGoodsByChildOrderId(childOrder.getChildOrderId());
//                childOrder.setSendOutGoods(sendOutGoods);
//            }
//        }
//        orderPage.setTotal(orderList.size());
//        return TableDataInfo.build(orderPage);
//    }

    @Override
    public Integer getStatementOrder(QueryOrderParam bo) {
        return sellerOrderMapper.getStatementOrder(bo);
    }

    /**
     * 获得申报商品长宽高
     */
    @Override
    public R<Object> getOrderSkuPackageInfo(Long orderId) {
        ErpCollectProductSkuPackageInfo skuPackageInfo = new ErpCollectProductSkuPackageInfo();
        skuPackageInfo.setOrder_id(orderId);

        // 获取子订单商品的长宽高重量
        
        // 获取子单skuCode
        ErpCollectProductSkuPackageInfo packageInfo = new ErpCollectProductSkuPackageInfo();
        List<ErpCollectProductSkuPackageInfo> skuPackageInfoList = new ArrayList<>();
        List<ErpSellerChildOrder> childOrderList = sellerChildOrderService.getChildOrderListByOrderId(orderId);
        for (ErpSellerChildOrder childOrder : childOrderList) {
            String skuCode = childOrder.getSkuCode();
            // 查询长宽高
            ErpCollectProductSku skuInfoBySkuCode = remoteCollectProductSkuService.getSkuInfoBySkuCode(skuCode);
            if (skuInfoBySkuCode != null) {
                // 填充
                packageInfo.setSku_code(skuCode);
                BigDecimal skuHeight = skuInfoBySkuCode.getSkuHeight();
                packageInfo.setGoods_height(skuHeight == null? 0: skuHeight.intValue());
                BigDecimal skuLength = skuInfoBySkuCode.getSkuLength();
                packageInfo.setGoods_length(skuLength == null ? 0: skuLength.intValue());
                BigDecimal skuWidth = skuInfoBySkuCode.getSkuWidth();
                packageInfo.setGoods_width(skuWidth == null ? 0 :skuWidth.intValue());
                Integer skuWeight = skuInfoBySkuCode.getSkuWeight();
                packageInfo.setGoods_weight(skuWeight == null ? null : skuWeight.toString());
                packageInfo.setOrder_id(orderId);
                packageInfo.setProduct_count(childOrder.getProductCount().toString());
                skuPackageInfoList.add(packageInfo);
                packageInfo = new ErpCollectProductSkuPackageInfo();
            }
        }
        BigDecimal goodsWeight = new BigDecimal(0);
        Integer goodsWidth = 0;
        Integer goodsLength = 0;
        Integer goodsHeight = 0;
        //开始计算长宽高
        for (ErpCollectProductSkuPackageInfo skuInfo : skuPackageInfoList) {
            BigDecimal skuWeight = new BigDecimal(skuInfo.getGoods_weight());
            if (skuWeight.subtract(goodsWeight).doubleValue() >= 0) {
                goodsLength = skuInfo.getGoods_length();
                goodsHeight = skuInfo.getGoods_height();
                goodsWidth = skuInfo.getGoods_width();
            }
            goodsWeight = goodsWeight.add(skuWeight);
        }
        skuPackageInfo.setGoods_weight(goodsWeight.toString());
        skuPackageInfo.setGoods_width(goodsWidth);
        skuPackageInfo.setGoods_length(goodsLength);
        skuPackageInfo.setGoods_height(goodsHeight);
        Integer type = null;
        ErpCollectProductSku erpCollectProductSku = new ErpCollectProductSku();
        ErpCollectProductExpand productExpand = new ErpCollectProductExpand();
        for (ErpCollectProductSkuPackageInfo sku : skuPackageInfoList) {
            
            erpCollectProductSku.setSkuCode(sku.getSku_code());
            List<ErpCollectProductSku> skuSelList = remoteCollectProductSkuService.getCollectProductSkuList(erpCollectProductSku);
            productExpand.setCollectProductId(skuSelList.get(0).getCollectProductId());
            R<Object> productExpandInfo = remoteCollectProductService.getCollectProductExpandInfo(productExpand);
            ErpCollectProductExpand collectProductExpand = JSONObject.parseObject(JSON.toJSONString(productExpandInfo.getData()), ErpCollectProductExpand.class);
            if (type == null) {
                type = collectProductExpand.getTemplateId();
            } else {
                //两个模板比较 取小的那个
                if (type > collectProductExpand.getTemplateId()) {
                    type = collectProductExpand.getTemplateId();
                }
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("skuPackageInfo", skuPackageInfo);
        map.put("skuPackageInfoList", skuPackageInfoList);
        map.put("type", type);
        return R.ok(map,"已查到");
    }

//    /**
//     * 新版获取物流服务
//     */
//    @Override
//    public List<AeLogisticsServiceName> logisticsServiceQueryNew(LogisticsServiceQueryDto logisticsServiceQueryDto) {
//        List<ErpCollectProductSkuPackageInfo> skuPackageInfoList = JSONArray.parseArray(logisticsServiceQueryDto.getSkuPackageInfoList(), ErpCollectProductSkuPackageInfo.class);
//        Map<String, Object> map = new HashMap<>();
//        //根据sellerLoginId获取店铺id
//
//        Long sellerId = iErpSellerStoreEmpowerService.queryBySellerLoginId(logisticsServiceQueryDto.getSellerLoginId());
//
//        map.put("sellerId", sellerId);
//        map.put("packageInfo", logisticsServiceQueryDto.getSkuPackageInfo());
//        map.put("skuPackageInfoList", skuPackageInfoList);
//
//        //将所有的信息发往Ae
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpLogistics/logisticsServiceQuery", map, String.class);
//        String body = (String) forEntity.getBody();
//        System.out.println(body);
//        String errorDesc = JSONObject.parseObject(body)
//                .getJSONObject("msg")
//                .getJSONObject("aliexpress_logistics_service_query_response")
//                .getJSONObject("result_response")
//                .getString("error_desc");
//        if (errorDesc != null) {
//            return null;
//        }
//        //将得到的数据抽出数组
//        List<AeLogisticsServiceName> aeLogisticsServiceNameList = JSONArray.parseArray(JSONObject.parseObject(body)
//                .getJSONObject("msg")
//                .getJSONObject("aliexpress_logistics_service_query_response")
//                .getJSONObject("result_response")
//                .getJSONObject("result_list")
//                .getString("result"), AeLogisticsServiceName.class);
//        List<AeLogisticsServiceName> filterList = new ArrayList<>();
//        for (AeLogisticsServiceName aeLogisticsService : aeLogisticsServiceNameList) {
//            String warehouseName = aeLogisticsService.getWarehouseName();
////            String filterName = "递四方东莞";
//            String filterName = "递四方深圳";
//            if (warehouseName.contains(filterName)) {
//                filterList.add(aeLogisticsService);
//            }
//        }
//        return filterList;
//    }
//
//    /**
//     * 旧版获取物流服务
//     *
//     * @param orderId
//     * @param sellerLoginId
//     * @return
//     */
//    @Override
//    public List<AeLogisticsServiceName> logisticsServiceQueryOld(Long orderId, String sellerLoginId) {
//        ErpCollectProductSkuPackageInfo skuPackageInfo = new ErpCollectProductSkuPackageInfo();
//        skuPackageInfo.setOrder_id(orderId);
//        //获取子订单商品的长宽高重量
//        List<ErpCollectProductSkuPackageInfo> skuPackageInfoList = iErpSellerChildOrderService.getChildOrderProduct(orderId);
//
//        BigDecimal goodsWeight = BigDecimal.ZERO;
//        Integer goodsWidth = 0;
//        Integer goodsLength = 0;
//        Integer goodsHeight = 0;
//        //开始计算长宽高
//        for (ErpCollectProductSkuPackageInfo skuInfo : skuPackageInfoList) {
//            BigDecimal skuWeight = new BigDecimal(skuInfo.getGoods_weight());
//            if (skuWeight.subtract(goodsWeight).compareTo(BigDecimal.ZERO.stripTrailingZeros()) >= 0) {
//                goodsLength = skuInfo.getGoods_length();
//                goodsHeight = skuInfo.getGoods_height();
//                goodsWidth = skuInfo.getGoods_width();
//            }
//            goodsWeight = goodsWeight.add(skuWeight);
//        }
////        goodsWeight = goodsWeight.divide(new BigDecimal(1000));
//        skuPackageInfo.setGoods_weight(goodsWeight.toString());
//        skuPackageInfo.setGoods_width(goodsWidth);
//        skuPackageInfo.setGoods_length(goodsLength);
//        skuPackageInfo.setGoods_height(goodsHeight);
//
//
//        Map<String, Object> map = new HashMap<>();
//        //根据sellerLoginId获取店铺id
//
//        Long sellerId = iErpSellerStoreEmpowerService.queryBySellerLoginId(sellerLoginId);
//
//        map.put("sellerId", sellerId);
//        map.put("packageInfo", skuPackageInfo);
//        map.put("skuPackageInfoList", skuPackageInfoList);
//
//        //将所有的信息发往Ae
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpLogistics/logisticsServiceQuery", map, String.class);
//        String body = (String) forEntity.getBody();
//        System.out.println(body);
//        String errorDesc = JSONObject.parseObject(body)
//                .getJSONObject("msg")
//                .getJSONObject("aliexpress_logistics_service_query_response")
//                .getJSONObject("result_response")
//                .getString("error_desc");
//        if (errorDesc != null) {
//            return null;
//        }
//        //将得到的数据抽出数组
//        List<AeLogisticsServiceName> aeLogisticsServiceNameList = JSONArray.parseArray(JSONObject.parseObject(body)
//                .getJSONObject("msg")
//                .getJSONObject("aliexpress_logistics_service_query_response")
//                .getJSONObject("result_response")
//                .getJSONObject("result_list")
//                .getString("result"), AeLogisticsServiceName.class);
//        List<AeLogisticsServiceName> filterList = new ArrayList<>();
//
//        for (AeLogisticsServiceName aeLogisticsService : aeLogisticsServiceNameList) {
//            String warehouseName = aeLogisticsService.getWarehouseName();
//            String filterName = "递四方深圳";
////            String filterName = "递四方东莞";
//            if (warehouseName.contains(filterName)) {
//                filterList.add(aeLogisticsService);
//            }
//        }
//        return filterList;
//    }
//
//    /**
//     * 线上声明发货
//     *
//     * @return
//     */
//    @Override
//    public R<String> sellerShipmentForTop(String childIds) {
//        //1、分割子订单
//        List<ErpSellerChildOrder> childOrderSendList = new ArrayList<>();
//        List<String> childIdList = new ArrayList<String>(Arrays.asList(childIds.split(",")));
//
//        //保证这几个子订单的orderId是同一个
//        Long orderId = null;
//        for (String childId : childIdList) {
//            //查看该子订单详情
//            ErpSellerChildOrder childOrder = erpSellerChildOrderMapper.selectById(childId);
//            //确认子订单是否存在
//            if (childOrder == null) {
//                return R.fail("未查找到该子订单");
//            }
//            if (orderId != null) {
//                if (!orderId.equals(childOrder.getOrderId())) {
//                    return R.fail("所选择子订单不属于同一订单");
//                }
//            }
//            orderId = childOrder.getOrderId();
//            //将该子订单放入可发货子订单
//            childOrderSendList.add(childOrder);
//        }
//        //获得该订单下应该有几个子订单
//        List<ErpSellerChildOrder> childOrderList = erpSellerChildOrderMapper.selectList(
//                new LambdaQueryWrapper<ErpSellerChildOrder>()
//                        .eq(ErpSellerChildOrder::getOrderId, orderId)
//        );
//        //是否全部发货
//        String sendType = "all";
//        if (childOrderSendList.size() != childOrderSendList.size()) {
//            sendType = "part";
//        }
//
//        //声明发货的话需要
//        //1、国际运单号 2、物流方案编码
//        //send_type 默认为all
//        //子交易单号
//        List<OrderShipmentForTopDto.SubTradeOrder> subTradeOrderlist = new ArrayList<>();
//        OrderShipmentForTopDto shipmentDto = new OrderShipmentForTopDto();
//        shipmentDto.setTrade_order_id(orderId);
//        //订单
//        ErpSellerOrder order = sellerOrderMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId)
//        );
//        ErpSellerStoreEmpower store = iErpSellerStoreEmpowerService.getEmpowerStoreByUserNick(order.getSellerLoginId());
//        shipmentDto.setSeller_id(store.getId());
//        List<ErpSendOutGoods> erpSendOutGoodsList = new ArrayList<>();
//        for (ErpSellerChildOrder childOrder : childOrderList) {
//            OrderShipmentForTopDto.SubTradeOrder subTradeOrder = new OrderShipmentForTopDto.SubTradeOrder();
//            subTradeOrder.setSend_type(sendType);
//            subTradeOrder.setSub_trade_order_index(childOrder.getOrderSortId());
//            List<OrderShipmentForTopDto.ShipmentList> shipmentList = new ArrayList<>();
//            //找到标记发货表对应信息
//            ErpSendOutGoods erpSendOutGoods = erpSendOutGoodsMapper.selectOne(
//                    new LambdaQueryWrapper<ErpSendOutGoods>()
//                            .eq(ErpSendOutGoods::getChildOrderId, childOrder.getChildOrderId())
//            );
//            erpSendOutGoodsList.add(erpSendOutGoods);
//            //判断是线上发货还是线下发货
//            OrderShipmentForTopDto.ShipmentList shipment = new OrderShipmentForTopDto.ShipmentList();
//            if (erpSendOutGoods.getType() == 0) {
//                shipment.setLogistics_no(erpSendOutGoods.getShippingNo());
//                shipment.setService_name(erpSendOutGoods.getSolutionCode());
//            } else if (erpSendOutGoods.getType() == 1) {
//                shipment.setLogistics_no(erpSendOutGoods.getShippingNo());
//                shipment.setService_name("OTHER");
////                shipment.setActual_carrier("colissimo");
//                shipment.setTracking_web_site("https://t.17track.net/zh-cn?nums=" + erpSendOutGoods.getShippingNo());
//            }
//            shipmentList.add(shipment);
//            subTradeOrder.setShipment_list(shipmentList);
//            subTradeOrderlist.add(subTradeOrder);
//        }
//
//
//        shipmentDto.setSub_trade_order_list(subTradeOrderlist);
//        System.out.println(JSONObject.toJSON(shipmentDto));
//        //将所有的信息发往Ae
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpLogistics/sellerShipmentForTop", shipmentDto, String.class);
//        String body = (String) forEntity.getBody();
//        System.out.println(body);
//        String code = JSONObject.parseObject(body).getString("code");
//        String msg = JSONObject.parseObject(body).getString("msg");
//        if (code.equals("500")) {
//            return R.fail(msg);
//        }
//        //查找erp预约表，修改声明发货状态
//        for (ErpSellerChildOrder childOrder : childOrderList) {
//            ErpHandoverOrderInfo erpHandoverOrderInfo = erpHandoverOrderInfoMapper.selectOne(
//                    new LambdaQueryWrapper<ErpHandoverOrderInfo>().like(ErpHandoverOrderInfo::getChildOrderIdList, childOrder.getChildOrderId())
//            );
//            erpHandoverOrderInfo.setShipmentForTopFlag(2);
//            erpHandoverOrderInfoMapper.updateById(erpHandoverOrderInfo);
//        }
//        //标记发货改为已声明发货
//        for (ErpSendOutGoods erpSendOutGoods : erpSendOutGoodsList) {
//            erpSendOutGoods.setShipmentForTopFlag(2);
//            erpSendOutGoodsMapper.updateById(erpSendOutGoods);
//        }
//        //订单状态改为108已声明发货 - 已完成
//        order.setErpInnerOrderStatus("108");
//        sellerOrderMapper.updateById(order);
//        return R.ok("声明发货成功");
//    }
//
//
//    @Override
//    public R<Object> freezeOrderAmount(Long orderId, Integer type) {
//        ErpOrderInfoStatistics statistics = orderInfoStatisticsMapper.selectOne(new LambdaQueryWrapper<ErpOrderInfoStatistics>().eq(ErpOrderInfoStatistics::getOrderId, orderId));
//        if (ObjectUtils.isEmpty(statistics)) {
//            return R.fail();
//        }
//        ErpSellerOrder sellerOrder = sellerOrderMapper.selectOne(new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId));
//        Long userId = empowerService.queryUserIdBySellerLoginId(sellerOrder.getSellerLoginId());
//        // 判断是否是先用后付
//        Boolean userIsPay = userInfoService.getUserIsPay(userId);
//        if (userIsPay) {
//            String statisticsProfit = statistics.getProfit();
//            if (ObjectUtils.isNull(statistics.getProfit())){
//                return R.fail();
//            }
//            BigDecimal profit = new BigDecimal(statisticsProfit);
//            if (profit.compareTo(BigDecimal.ZERO) < 0) { // 利润为负数
//                return R.fail();
//            }
//            String ratioPre = configService.selectConfigByKey("order_charging_ratio");
//            BigDecimal ratio = new BigDecimal(ratioPre);
//            ratio = ratio.movePointLeft(2); // 扣费比例,左移两位
//            profit = profit.multiply(ratio); // 最终扣费金额
//            R<Object> returnR = new R<>();
//            if (type == 0) { // 冻结金额
//                ErpSellerStoreWalletLog walletLog = walletLogMapper.selectOne(new LambdaQueryWrapper<ErpSellerStoreWalletLog>()
//                        .eq(ErpSellerStoreWalletLog::getOrderNumber, orderId)
//                        .eq(ErpSellerStoreWalletLog::getRemark, "先用后付冻结")
//                        .last("limit 1"));
//                if (walletLog == null) {
//                    returnR = walletService.updateWallet(FlowType.FREEZE.getCode(), ExpenseType.ORDERPAYMENT.getCode(), PayType.YE.getCode(), profit, userId, orderId.toString(), "先用后付冻结");
//                }
//            } else if (type == 1) { // 扣款
//                returnR = walletService.updateWallet(FlowType.DEDUCTION.getCode(), ExpenseType.ORDERPAYMENT.getCode(), PayType.YE.getCode(), profit, userId, orderId.toString(), "先用后付扣款");
//            } else if (type == 2) { // 解冻
//                returnR = walletService.updateWallet(FlowType.FREEZE.getCode(), ExpenseType.ORDERREFUND.getCode(), PayType.YE.getCode(), profit, userId, orderId.toString(), "先用后付退款");
//            }
//            return returnR;
//        }
//        return R.fail();
//    }

    @Override
    public List<ErpSellerOrder> getStoreList() {
        LambdaQueryWrapper<ErpSellerOrder> wrapper = new LambdaQueryWrapper<ErpSellerOrder>()
                .groupBy(ErpSellerOrder::getSellerLoginId)
                .select(ErpSellerOrder::getSellerLoginId, ErpSellerOrder::getSellerSignerFullname);
        List<ErpSellerOrder> orderList = sellerOrderMapper.selectList(wrapper);
        return orderList;
    }

    @Override
    public R<Object> queryPurchaseInfo(Long childOrderId) {
        ErpSellerChildOrderExtend childOrderExtend = erpSellerChildOrderExtendMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerChildOrderExtend>()
                        .eq(ErpSellerChildOrderExtend::getChildOrderId, childOrderId)
        );
        if (childOrderExtend != null) {
            return R.ok(childOrderExtend);
        } else {
            return R.ok(null,"信息未填写");
        }

    }
    @Override
    public ErpSellerOrder queryByOrderId(Long orderId) {
        return sellerOrderMapper.selectOne(new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId));
    }
    /**
     * 第三版0803 TODO 权限控制 获取订单列表
     */
    @Override
    public TableDataInfo<ErpSellerOrderSelVo> selectOrderListNew(PageQuery pageQuery, QueryOrderParam param) {
        param.setType(1);
        if (param.getType() == 0) {
            if (SecurityUtils.getUserId() != 1) {
                param.setUserId(SecurityUtils.getUserId());
            }
        }

        Page<ErpSellerOrderSelVo> variedOrderPageList = sellerOrderMapper.selectOrderSelVoList(pageQuery.build(), param);
        variedOrderPageList.setTotal(variedOrderPageList.getTotal());
        List<ErpSellerOrderSelVo> records = variedOrderPageList.getRecords();
        // 获取订单模块以外的信息 地址，统计信息
        for (ErpSellerOrderSelVo sellerOrderSelVo : records) {
            sellerOrderSelVo.setQuotationCurrency(sellerOrderSelVo.getPayCurrencyCode());
            Long orderId = sellerOrderSelVo.getOrderId();
            // 重新查看订单统计表是否有数据
            R<Object> orderStatisticsR = remoteOrderStatisticsService.getByOrderId(sellerOrderSelVo.getOrderId().toString());

            // 保存数据
            ErpSellerOrder sellerOrder = sellerOrderMapper.queryOrderByOrderId(sellerOrderSelVo.getOrderId());
            List<ErpSellerChildOrder> childOrderList = sellerChildOrderService.getChildOrderListByOrderId(sellerOrder.getOrderId());
            sellerOrder.setSellerChildOrderList(childOrderList);
            // 没有统计数据，则插入
            if(orderStatisticsR.getData() == null){
                remoteOrderStatisticsService.saveOrderProfitInfo(sellerOrder);
            }else {
                // 不为空
                String orderStatisticsString = JSONObject.toJSONString(orderStatisticsR.getData());
                ErpOrderInfoStatistics orderInfoStatistics = JSONObject.parseObject(orderStatisticsString, ErpOrderInfoStatistics.class);
                if(orderInfoStatistics.getProfit() == null){
                    remoteOrderStatisticsService.saveOrderProfitInfo(sellerOrder);
                }
            }
//             装载数据
            orderStatisticsR = remoteOrderStatisticsService.getByOrderId(sellerOrderSelVo.getOrderId().toString());
            String orderStatisticsString = JSONObject.toJSONString(orderStatisticsR.getData());
            ErpOrderInfoStatistics orderInfoStatistics = JSONObject.parseObject(orderStatisticsString, ErpOrderInfoStatistics.class);

            if(orderStatisticsR.getCode() == 200 && orderStatisticsR.getData() != null){
//                交易佣金
                sellerOrderSelVo.setEscrowFeeRate(orderInfoStatistics.getEscrowFeeRate());
//                联盟佣金比例
                sellerOrderSelVo.setAfflicateFeeRate(orderInfoStatistics.getAfflicateFeeRate());
//                预估利润
                sellerOrderSelVo.setEstimatedProfit(orderInfoStatistics.getProfit());
//                付款金额
                sellerOrderSelVo.setPayAmount(orderInfoStatistics.getPayPrice());
            }

            // 获取地址信息
            String country = "CN";
            AeStoreOrderReceiptAddress address = remoteAeOrderAddrService.getAddressByOrderId(orderId);
            if (address != null) {
                sellerOrderSelVo.setAeStoreOrderReceiptAddress(address);
                country = address.getCountry();
            }
            ErpSellerChildOrderExtend childOrderExtend = erpSellerChildOrderExtendMapper.selectOne(new LambdaQueryWrapper<ErpSellerChildOrderExtend>()
                    .eq(ErpSellerChildOrderExtend::getOrderId, orderId).last("limit 1"));
            if (childOrderExtend != null) {
                sellerOrderSelVo.setConsignmentNo(childOrderExtend.getConsignmentNo());
            }

            // 获取店铺id，判断是否是测评单
            Long storeId = 0L;
            R<Object> sellerStoreEmpowerByCnCode = remoteSellerStoreService.getSellerStoreEmpowerByCnCode(sellerOrderSelVo.getSellerLoginId());
            if (sellerStoreEmpowerByCnCode.getCode() == 200 && sellerStoreEmpowerByCnCode.getData() != null) {
                String userString = JSONObject.toJSONString(sellerStoreEmpowerByCnCode.getData());
                ErpSellerStoreEmpower erpSellerStoreEmpower = JSONObject.parseObject(userString, ErpSellerStoreEmpower.class);
                storeId = erpSellerStoreEmpower.getId();
            }

            List<ErpSellerChildOrderSelVo> erpSellerChildOrderSelVos = erpSellerChildOrderMapper.selectChildOrderListByOrderId(orderId);

            for (ErpSellerChildOrderSelVo sel : erpSellerChildOrderSelVos) {
                // 获取子订单采购金额
                /*R<Object> byChildOrderId = remoteOrderStatisticsService.getByChildOrderId(sel.getChildOrderId());
                if (byChildOrderId.getCode() == 200) {
                    sel.setSkuPrice(JSONObject.toJSONString(byChildOrderId.getData()));
                }*/
                
                // 获取采购链接
                ErpCollectProductSku skuInfoBySkuCode = remoteCollectProductSkuService.getSkuInfoBySkuCode(sel.getSkuCode());
                if (skuInfoBySkuCode != null) {
                    sel.setCollectProductId(skuInfoBySkuCode.getCollectProductId());
                    sel.setSkuBuyLink(skuInfoBySkuCode.getSkuBuyLink());
                }

                // 获取sku规格
                R<Object> skuPropertyIdsR = remoteCollectProductSkuService.getSpecBySkuCodeNew(sel.getSkuCode());
                if (skuPropertyIdsR.getCode() == 200) {
                    sel.setSkuPropertyIds(skuPropertyIdsR.getData().toString());
                }

                // 是否填写采购凭证
                if (ObjectUtils.isNotEmpty(sel.getProof())) {
                    sel.setIsProof(1);
                }

                // TODO 这个字段暂时没发现哪里用到
//                R<Object> childOrderStatisticsR = remoteOrderStatisticsService.getByChildOrderId(sel.getChildOrderId());
//                if(childOrderStatisticsR.getCode() == 200 && childOrderStatisticsR.getData() != null){
//                    String childOrderStatisticsString = JSONObject.toJSONString(childOrderStatisticsR);
//                    ErpChildOrderStatistics childOrderStatistics = JSONObject.parseObject(childOrderStatisticsString, ErpChildOrderStatistics.class);
//
//                    sel.setChildAmount(childOrderStatistics.getChildAmount());
//                }

                //判断是否有可能是测评单
                String gmtPayTime = sellerOrderSelVo.getGmtPayTime();
                if (ObjectUtils.isNotEmpty(gmtPayTime)) {
                    Integer evaluation = remoteEvaluationService.doubtEvaluation(country, storeId, gmtPayTime, sel.getProductCount(), sel.getSkuCode());
                    if (!Objects.isNull(evaluation)) {
                        sel.setIsEvaluation(evaluation);
                    }
                }
                //循环子订单
                sellerOrderSelVo.setSellerChildOrderList(erpSellerChildOrderSelVos);
            }

            //加入日志
            ErpSellerOrderLog log = sellerOrderLogService.getStatusIntro(orderId);
            if (ObjectUtils.isNotEmpty(log)) {
                sellerOrderSelVo.setStatusIntro(log.getStatusIntro());
            }
        }

        return TableDataInfo.build(variedOrderPageList);
    }

    @Override
    public ErpSellerOrder getInfoByOrderId(Long orderId) {
        return sellerOrderMapper.selectOne(new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId,orderId));
    }

}
